package com.xiecong.task;

import com.aliyuncs.exceptions.ClientException;
import com.xiecong.mapper.EmpMapper;
import com.xiecong.utils.AliyunOSSOperator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
//@Component
public class CleanImageTask {

    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;

    @Autowired
    private EmpMapper empMapper;

    @Scheduled(cron = "0/10 * * * * ?")
    public void removeOSSImage(){
        log.info("清理垃圾图片的任务正在运行");
        //1、查询出阿里oss上的所有的图片名称
        List<String> ossList = new ArrayList<>();
        try {
            ossList = aliyunOSSOperator.listImages();
        } catch (Exception e) {
            log.error("查询oss图片列表失败",e);
        }
        log.info("oss上的图片共有{}张", ossList.size());
        if(!CollectionUtils.isEmpty(ossList)) {
            //2、查询出数据库emp表中的所有的图片
            // 数据库的图片地址：https://sz152.oss-cn-shenzhen.aliyuncs.com/2025/05/e94191c6-c9d0-4832-81b6-37d4465a1067.png
            // 阿里上的图片: 2025/05/e94191c6-c9d0-4832-81b6-37d4465a1067.png
            List<String> imagesInDB = empMapper.selectAllImages();
            log.info("数据库中的图片有{}张", imagesInDB.size());
            // 把数据库的图片地址进行截取，只保留与oss相同格式
            List<String> imagesInDBUrls = new ArrayList<>();
            if(!CollectionUtils.isEmpty(imagesInDB)){
                // 处理后的数据图片地址
               imagesInDBUrls = imagesInDB.stream().map(image -> image.replaceFirst("https://sz152.oss-cn-shenzhen.aliyuncs.com/", ""))
                       .collect(Collectors.toList());
            }
            //3、oss-emp 集合相减, ossList里包含magesInDBUrls内容，全删除掉
            // oos[1.jpg,2.jpg,3.jpg], imagesInDBUrls[2.jpg] removeAll, oos[1.jpg,3.jpg]
            ossList.removeAll(imagesInDBUrls);
            //4、调用oss删除图片
            log.info("要删除的图片有{}张", ossList.size());
            if(!CollectionUtils.isEmpty(ossList)){
                // 有垃圾图片
                try {
                    aliyunOSSOperator.deleteBatch(ossList);
                    log.info("删除{}张垃圾图片成功", ossList.size());
                } catch (Exception e) {
                    log.error("批量删除阿里云上图片失败", e);
                }
            }
        }
        log.info("清理垃圾图片的任务已经结束");
    }
}
